package com.android.love.net;

import java.util.concurrent.atomic.AtomicBoolean;

import android.os.AsyncTask;
import android.os.Handler;

import com.android.love.util.Constant;
import com.android.love.view.CustomViewPager;

public class AutoTask implements Runnable ,Constant{
	private Thread task;
	private Handler handler;

	AtomicBoolean mPause = new AtomicBoolean(false);
	private CustomViewPager mViewPager;

	public AutoTask(CustomViewPager mViewPager,Handler handler) {
		// task = this;
		this.mViewPager = mViewPager;
		this.handler=handler;
		task = new Thread(this);
		task.start();
		mViewPager
				.setMoveAndUpListener(new CustomViewPager.onMoveAndUpListener() {

					public void onMove() {
						// pauseAutoTask();
						pause();
					}

					public void onUp() {
						// resumeAutoTask();
						resume();
					}

				});
	}

	// @Override
	// protected Void doInBackground(Void... params) {
	// while (task != null && !Thread.interrupted())
	// try {
	// Thread.sleep(4000L);
	// publishProgress(new Void[0]);
	// } catch (InterruptedException localInterruptedException) {
	// localInterruptedException.printStackTrace();
	// Thread.interrupted();
	// }
	// return null;
	// }

	protected void onProgressUpdate() {
		if (!this.mPause.get()) {
			// int i=BannerView.this.mViewPager.getCurrentItem();
			// BannerView.this.mViewPager.setCurrentItem(i + 1);
			handler.sendEmptyMessage(VIEWPAGER);
//			if (mViewPager.getCurrentItem() < mViewPager.getAdapter()
//					.getCount() - 1)
//				mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
//			else
//				mViewPager.setCurrentItem(0);
		}
	}

	public void pause() {
		if (task != null)
			this.mPause.set(true);
	}

	public void resume() {
		if (task != null)
			this.mPause.set(false);
	}

	public void stop() {
		if (task != null) {
			task.interrupt();
			task = null;
		}
	}

	@Override
	public void run() {
		Thread thisThread = Thread.currentThread();
		while (task != null && !Thread.interrupted())
			try {
				Thread.sleep(4000L);
				onProgressUpdate();
			} catch (InterruptedException localInterruptedException) {
				localInterruptedException.printStackTrace();
				Thread.interrupted();
			}

	}

}
